﻿using System;
using CqBuiltinService.Options;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using RedisService.Options;
using SuperShopInfrastructure.Weixin.Options;
using UploadService.Option;
using CqBuiltinService.Logging;
using CqBuiltinService.Extensions;
using CqBuiltinService.Documents;
using SuperShopRepository.Dbs;
using CqBuiltinService.Db;
using CqBuiltinService.Redis;
using SuperShopApi.Extensions;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using CqCore.Logging;
using CqBuiltinService.Requests;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace SuperShopApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<RuntimeOption>(Configuration.GetSection("Runtime"));
            services.Configure<LoggingOption>(Configuration.GetSection("Logging"));
            services.Configure<DocumentOption>(Configuration.GetSection("Document"));
            services.Configure<ImageServiceOption>(Configuration.GetSection("ImgConfig"));
            services.Configure<WxConfigOption>(Configuration.GetSection("WxConfig"));
            services.Configure<RedisOption>(Configuration.GetSection("Redis"));
            services.AddBuiltinLogging(AppDomain.CurrentDomain.GetFilePath("settings/NLog.config"));

            services.AddBuiltinDocument();
            services.AddHttpClient();
            services.AddDb<SuperShopCustomerDb>(Configuration.GetSection("Database:ConnectString").Value);

            services.AddRedis();
            //services.AddUploadService();
            services.AddWxHelper();

            //业务服务注册
            services.AddBusinessServices();
            services.AddHttpContextAccessor();
            services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
            services.AddMvc((service) =>
            {
                //service.Filters.Add(typeof(RequestingTrackFilter));
            })
            .AddJsonOptions(opt=> {
                opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();//json字符串大小写原样输出
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var logger = app.ApplicationServices.GetService<ILogRecorder<Startup>>();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseBuiltinDocument();

            app.UseCors(builder =>
            {
                builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .SetIsOriginAllowed((url) => true) //Access-Control-Allow-Origin
                    .AllowCredentials(); //Access-Control-Allow-Credentials
            });
            app.UseBuiltinExceptionTracing();

            //虚拟目录
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "E:\\wwwroot\\SuperiorImg")),
                RequestPath = new PathString("/SuperiorImages")
            });

            app.Map("/well-known/ready", builder =>
            {
                builder.Run(async context =>
                {
                    await context.Response.WriteAsync("service is ready.");
                });
            });
            app.UseMvc();
            logger.Info(new EventData
            {
                Type = "Startup",
                Message = "启动完成"
            });
        }
    }
}
